<?php
/**
 * Created by PhpStorm.
 * User: maqun
 * Date: 2016/2/29
 * Time: 12:35
 * 问题导出
 */
class ExportAction extends BaseAction{

    protected $language_name=array();


    public function _initialize(){
        self::$action = 2;
        parent::_initialize();
        $this->language_name = C('OJ_LAN_NAME');
    }

    #问题导出
    public function exportPage(){

        set_param_key('post');
        $this->display('export');
    }
    #问题导出提交
    public function export(){
//        dump($this->_post());exit;
        $do  = $this->_param('do');
        $cid = $this->_param('cid');
        $in  = $this->_param('in');
        $postkey = $this->_param('postkey');

        $result = array();
        if(isset($do)||isset($cid)){
            if(isset($in)&&strlen($in)>0){
                if(!check_param_key($postkey,'post')){
                    $this->error('postkey error');
                }

                $result = D('Problem')->where("problem_id in($in)")->select();
                $filename="-$in";
            }elseif(isset($cid)){
                if(!check_param_key($this->_get('getkey'),'get')){
                    $this->error('getkey error');
                }
                $cid=intval($cid);
                $res = M('Contest')->field('title')->where("contest_id='$cid'")->select();
                $filename='-'.$res[0]['title'];

                $result = D('Problem')
                        ->where("problem_id in(select problem_id from contest_problem where contest_id=$cid)")
                        ->select();
            }else{
                if(!check_param_key($postkey,'post')){
                    $this->error('postkey error');
                }
                $start = intval($this->_post('start'));
                $end  = intval($this->_post('end'));

                $result = D('Problem')->where("problem_id>=$start and problem_id<=$end")->select();
                $filename="-$start-$end";
            }

            $submit = $this->_post('submit');
            if (isset($submit)&& ($submit == "Export"))
                header ( 'Content-Type: text/xml' );
            else {
                header ( "content-type: application/file" );
                header ( "content-disposition:   attachment;   filename=\"fps-".$_SESSION['USER']['user_id'].$filename.".xml\"" );
            }
            echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
            echo '<fps version="1.1" url="http://code.google.com/p/freeproblemset/">'."\n";
            echo '<generator name="HUSTOJ" url="http://code.google.com/p/hustoj/"/>'."\n";
            foreach($result as $key=>$val){
                echo '<item>'."\n";
                echo '<title><![CDATA['.$val['title'].']]></title>'."\n";
                echo '<time_limit unit="s"><![CDATA['.$val['time_limit'].']]></time_limit>'."\n";
                echo '<memory_limit unit="mb"><![CDATA['.$val['time_limit'].']]></memory_limit>'."\n";

                $did=array();
                $this->fixImageURL($val['description'],$did);
                $this->fixImageURL($val['input'],$did);
                $this->fixImageURL($val['output'],$did);
                $this->fixImageURL($val['hint'],$did);

                echo '<description><![CDATA['.$val['description'].']]></description>'."\n";
                echo '<input><![CDATA['.$val['input'].']]></input>'."\n";
                echo '<output><![CDATA['.$val['output'].']]></output>'."\n";
                echo '<sample_input><![CDATA['.$val['sample_input'].']]></sample_input>'."\n";
                echo '<sample_output><![CDATA['.$val['sample_output'].']]></sample_output>'."\n";

//                echo $this->printTestCases($val['problem_id'],C('OJ_DATA'));

                echo '<hint><![CDATA['.$val['hint'].']]></hint>'."\n";
                echo '<source><![CDATA['.$val['source'].']]></source>'."\n";


                for($lang=0;$lang<count($this->language_name);$lang++){
                    $solution = $this->getSolution($val['problem_id'],$lang);
                    if ($solution['language']){
                        echo '<solution language="'.$solution['language'].'"><![CDATA['.$this->fixcdata($solution['source_code']).']]></solution>';
                    }
                }
                if($val['spj'] != 0){
                    $filec  = "$OJ_DATA/".$val['problem_id']."/spj.c";
                    $filecc = "$OJ_DATA/".$val['problem_id']."/spj.cc";
                    if(file_exists( $filec )){
                        echo "<spj language=\"C\"><![CDATA[";
                        $string = file_get_contents ($filec);
                        echo $this->fixcdata();
                        echo "]]></spj>";
                    }elseif(file_exists($filecc)){
                        echo "<spj language=\"C++\"><![CDATA[";
                        echo $this->fixcdata(file_get_contents ($filecc ));
                        echo "]]></spj>";
                    }
                }
                echo "\n</item>";
            }
            echo "\n</fps>";
        }
    }

    public function fixcdata($content){
        return str_replace("]]>","]]]]><![CDATA[>",$content);
    }

    public function getImages($content){
        preg_match_all("<[iI][mM][gG][^<>]+[sS][rR][cC]=\"?([^ \"\>]+)/?>",$content,$images);
        return $images;
    }
    public function fixurl($img_url){
        $img_url=htmlspecialchars_decode( $img_url);

        if (substr($img_url,0,7)!="http://"){
            if(substr($img_url,0,1)=="/"){
                $ret='http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$img_url;
            }else{
                $path= dirname($_SERVER['PHP_SELF']);
                $ret='http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$path."/../".$img_url;
            }
        }else{
            $ret=$img_url;
        }
        return  $ret;
    }

    public function image_base64_encode($img_url){
        $img_url=$this->fixurl($img_url);
        $handle = @fopen($img_url, "rb");
        if($handle){
            $contents = stream_get_contents($handle);
            $encoded_img= base64_encode($contents);
            fclose($handle);
            return $encoded_img;
        }else
            return false;
    }

    public function fixImageURL(&$html,&$did){
       $images=$this->getImages($html);
       $imgs=array_unique($images[1]);
       foreach($imgs as $img){
              $html=str_replace($img,$this->fixurl($img),$html);
              //print_r($did);
              if(!in_array($img,$did)){
                  $base64=$this->image_base64_encode($img);
                  if($base64){
                      echo "<img><src><![CDATA[";
                      echo fixurl($img);
                      echo "]]></src><base64><![CDATA[";
                      echo $base64;
                      echo "]]></base64></img>";
                 }
                 array_push($did,$img);
             }
       }
    }
    public function getSolution($pid,$lang){
        $ret = array('language'=>'','source_code'=>'');
        $res = M('Solution')
                ->field('solution_id,language')
                ->where("problem_id=$pid and result=4 and language={$lang}")
                ->limit(1)
                ->select();

		$solution_id=$res[0]['solution_id'];
		$ret['language'] = !empty($res) ? $this->language_name[$res[0]['language']] : '';

        $source = M('SourceCode')
                  ->field('source')
                  ->where("solution_id={$solution_id}")
                  ->select();

        $ret['source_code'] = !empty($source) ? $source[0]['source']:'';

        return $ret;
    }
}